<template>
  <div class="container">
    <el-card>
      <!-- 面包屑 导航 -->
      <el-row v-if="isShowSubjectName">
        <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item class="black" :to="{ path: '/subjects/list' }"
            >学科管理</el-breadcrumb-item
          >
          <el-breadcrumb-item>{{ subjectName }}</el-breadcrumb-item>
          <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        </el-breadcrumb> -->
        <div class="title">
          <span>学科管理</span>> <span>{{ subjectName }}</span
          >>
          <span>目录管理</span>
        </div>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="15">
          <el-form
            ref="objectForm"
            :inline="true"
            :model="queryInfo"
            class="demo-form-inline"
          >
            <el-form-item label="目录名称">
              <el-input v-model="queryInfo.directoryName"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryInfo.state" placeholder="请选择">
                <el-option label="启用" :value="1"></el-option>
                <el-option label="禁用" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="reSet">清除</el-button>
              <el-button type="primary" @click="onSearch">搜索</el-button>
            </el-form-item>
          </el-form></el-col
        >
        <el-col :span="9">
          <a
            class="toxueke"
            @click="$router.push('/subjects/list')"
            v-if="isShowSubjectName"
            >⬅返回学科</a
          >
          <el-button
            type="success"
            class="clear-right"
            icon="el-icon-edit"
            @click="newDirectoryName"
            >新增目录</el-button
          >
        </el-col>
      </el-row>
      <!-- 头部表单 -->
      <!-- <el-form
        ref="objectForm"
        :inline="true"
        :model="queryInfo"
        class="demo-form-inline"
      >
        <el-form-item label="目录名称">
          <el-input v-model="queryInfo.directoryName"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryInfo.state" placeholder="请选择">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="reSet">清除</el-button>
          <el-button type="primary" @click="onSearch">搜索</el-button>
        </el-form-item>
      </el-form> -->
      <!-- <a @click="$router.back()" v-if="isShowSubjectName">⬅返回学科</a>
      <el-button
        type="success"
        class="clear-right"
        icon="el-icon-edit"
        @click="newDirectoryName"
        >新增目录</el-button
      > -->

      <!-- 消息提示 -->
      <el-alert :title="alertTitle" type="info" show-icon :closable="false">
      </el-alert>

      <!-- 学科目录表格 -->
      <el-table :data="allDirectoryNameList" stripe>
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="subjectName" label="所属学科"> </el-table-column>
        <el-table-column prop="directoryName" label="目录名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者"> </el-table-column>
        <el-table-column prop="addDate" label="创建日期">
          <template slot-scope="scope">
            {{ scope.row.addDate | parseTime }}
          </template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量"> </el-table-column
        ><el-table-column prop="date" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.state === 1">已启用</span>
            <span v-else>已禁用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.state"
              :disabled="scope.row.state === 0 ? true : false"
              size="mini"
              icon="el-icon-edit"
              @click="change(scope.row)"
              >禁用</el-button
            >
            <el-button
              v-else
              :disabled="scope.row.state === 1 ? true : false"
              size="mini"
              icon="el-icon-edit"
              @click="change(scope.row)"
              >启用</el-button
            >
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              :disabled="scope.row.state === 1 ? true : false"
              @click="editMulu(scope.row)"
              >修改</el-button
            >
            <!-- @click="edit(scope.row)" -->

            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              :disabled="scope.row.state === 1 ? true : false"
              @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页操作 -->

      <el-pagination
        class="fenye"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts"
      >
      </el-pagination>
    </el-card>

    <!-- 新增目录的对话 -->
    <directory-add
      :isFromSubjectInto="isFromSubjectInto"
      @canelDialog="canelDialog"
      @editDirectoryFather="editDirectoryFather"
      :subjectIDD="subjectID"
      :directoryNameF="rowName"
      :fromsubjectID="fromsubjectID"
      @addDirectory="addDirectory"
      :title="title"
      :subjectSimpleList="subjectSimpleList"
      v-if="isShowDirectoryAdd"
    ></directory-add>
    <!-- :subjectID="subjectID" -->
  </div>
</template>

<script>
// 添加 对话框组件
import DirectoryAdd from "@/module-hmmm/components/directorys-add";
import {
  list,
  simple,
  add,
  changeState,
  remove,
  detail,
  update,
} from "@/api/hmmm/directorys.js";
import {
  list as subjectsList,
  simple as subjectsSimple,
} from "@/api/hmmm/subjects.js";
export default {
  name: "Directorys.vue",
  data() {
    return {
      // 页码值 查询信息
      queryInfo: {
        page: 1,
        pagesize: 10,
        directoryName: null,
        subjectID: null,
        state: null,
      },
      // 所有目录列表
      allDirectoryNameList: [],
      // 学科列表总数
      counts: 0,
      // 新增目录的对话框 显示与隐藏
      addDialogVisible: false,
      // 选中 学科Id
      subjectID: null,
      // 新增 目录名称
      directoryName: "",
      // 学科 简单列表
      subjectSimpleList: [],
      // 编辑目录对话框的显示与隐藏
      editDialogVisible: false,
      // 绑定的编辑表单
      editForm: "",
      // 编辑表单的验证规则
      editFormRules: {
        directoryName: [
          { required: true, message: "请输入目录名称", trigger: "blur" },
        ],
      },
      // 搜索分页
      searchFenye: "",
      // 根据 条数 隐藏分页
      isShowFenYe: true,
      // 添加对话框的显示与隐藏
      isShowDirectoryAdd: false,
      // 控制添加 对话框的提示标题
      title: "",
      // 学科项的选中id
      subjectIDD: "",
      // 编辑目录行的id
      rowId: "",
      // 编辑当前行的名称
      rowName: "",
      // 学科名字
      subjectName: "",
      // 是否显示标题
      isShowSubjectName: false,
      // 添加框 按需显示
      isFromSubjectInto: false,
      // 穿来的id
      fromsubjectID: null,
    };
  },
  methods: {
    // 处理url地址
    urlChuli() {
      // let url = 'http://ajax.frontend.itheima.net"3006/api/jsonp?name=zhangsan&ang=18&sex=boy'
      const index = location.hash.indexOf("?");
      console.log(index);
      if (index === -1) {
        return true;
      }
      const query = location.hash.slice(index + 1);
      // console.log(url);
      let arr = query.split("&");
      console.log(arr);
      let obj = {};
      arr.forEach((item) => {
        item = item.split("=");
        obj[item[0]] = item[1];
      });
      console.log(obj);
      this.queryInfo.subjectID=obj.id
    },

    // 获取学科目录列表
    async getList() {
      // location
      console.log(location);
      // this.queryInfo.subjectID = location.query.id;
      console.log("this.queryInfo");
      console.log(this.queryInfo);
      const { data } = await list(this.queryInfo);
      console.log(data);
      // 保存数据
      this.allDirectoryNameList = data.items;

      console.log(data.items);
      // 学科列表总数
      this.counts = data.counts;
    },

    // 每页条数 改变事件
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      if (this.searchFenye === "search") {
        this.getList();
      } else {
        this.getList();
      }
    },

    // 页码值改变事件
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryInfo.page = val;
      if (this.searchFenye === "search") {
        this.getList();
      } else {
        this.getList();
      }
    },

    // 点击搜索
    async onSearch() {
      if (this.queryInfo.page !== 1) {
        this.queryInfo.page = 1;
      }
      this.searchFenye = "search";
      this.getList();
    },

    // 点击清除 清空表单
    reSet() {
      console.log(111);
      this.queryInfo.directoryName = null;
      this.queryInfo.state = null;
      this.queryInfo.subjectID = null;
      this.getList();
    },

    // 新增 目录
    async newDirectoryName() {
      this.isShowDirectoryAdd = true;
      this.title = "add";
      // 获取学科 列表
      const { data } = await subjectsSimple();
      console.log(data);
      // 传来的id
      this.fromsubjectID = this.queryInfo.subjectID;
      this.subjectSimpleList = data;
    },

    // 点击禁用 更改状态
    async change(row) {
      console.log(row);
      row.state = row.state === 0 ? 1 : 0;
      const res = await changeState(row);
      console.log(res);
      this.$message.success("操作成功");
      // this.getList();
    },

    // 删除目录
    async del(row) {
      // 提示 是否删除
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err;
      });
      console.log(result);
      if (result !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // 删除操作
      const res = await remove(row);
      console.log(res);
      if (res.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getList();

      const index = this.allDirectoryNameList.findIndex((item) => {
        return item.id === row.id;
      });
      console.log(index);

      if (index === 0) {
        this.queryInfo.page = this.queryInfo.page - 1;
        this.getList();
      }
    },

    // 获取添加 对话框 传来的数据
    async addDirectory(val) {
      console.log(val);

      // 操作 添加 还是编辑
      if (val.type === "add") {
        const res = await add(val);
        console.log(res);
        if (res.status !== 200) {
          return this.$message.error("新增目录失败");
        }
        this.$message.success("新增目录成功");
      }

      // 刷新列表
      this.getList();
      // 关闭添加框
      this.isShowDirectoryAdd = false;
    },

    // 点击编辑 编辑目录 展示目录并传值
    async editMulu(row) {
      this.rowId = row.id;
      console.log(row);
      this.title = "edit";
      // 展示 对话框
      this.isShowDirectoryAdd = true;
      // 获取学科 列表
      const { data } = await subjectsSimple();
      console.log(data);
      this.subjectSimpleList = data;
      this.subjectID = row.subjectID;
      this.rowName = row.directoryName;
    },

    // 对子传父值操作 编辑当前目录
    async editDirectoryFather(val) {
      console.log(val);
      const res = await update({ ...val, id: this.rowId });
      console.log(res);
      if (res.status !== 200) {
        return this.$message.error("修改失败");
      }
      this.getList();
      this.$message.success("修改成功");
      // 关闭对话框
      this.isShowDirectoryAdd = false;
    },

    // 取消操作 关闭对话框
    canelDialog() {
      this.isShowDirectoryAdd = false;
    },
  },

  // created() {
  // },
  mounted() {
    // debugger;
    this.urlChuli();
    this.getList();
  },
  computed: {
    alertTitle() {
      return `数据一共${this.counts}条`;
    },
  },
  components: {
    DirectoryAdd,
  },
  beforeRouteEnter(to, from, next) {
    console.log(123);
    console.log(to);
    console.log(from);
    next((vm) => {
      console.log(vm);
      // 通过 `vm` 访问组件实例
      if (to.query.id) {
        vm.queryInfo.subjectID = Number(to.query.id);
        vm.isFromSubjectInto = true;
      }
      vm.subjectName = to.query.name;
      if (to.query.name) {
        vm.isShowSubjectName = true;
      }
    });
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当守卫执行前，组件实例还没被创建
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变，但是该组件被复用时调用
    // 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
    // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    console.log(to);
    console.log(from);
    next();
  },
  watch: {
    $route: {
      handler(to, from) {
        console.log(to);
        console.log(from);
      },
      immediate: true,
    },
  },
};
</script>

<style scoped>
.clear-right {
  float: right;
}

.el-alert {
  margin-bottom: 10px;
}

.el-breadcrumb {
  margin-bottom: 10px;
}

.el-breadcrumb__inner {
  color: #606266;
}

.toxueke {
  font-size: 12px;
  color: blue;
  position: absolute;
  top: 15px;
  right: 140px;
}

.title {
  color: black;
  margin-bottom: 10px;
  font-size: 13px;
}
.fenye {
  float: right;
  margin-right: 50px;
}
</style>
